<template>
    <div>
        <!-- 选择商品弹窗 -->
        <el-dialog :title="title" :visible.sync="showChooseUser" :close-on-click-modal="false" 
            width="70%" @close="closeDialog" center append-to-body>
            <div class="goods_list">
                <div class="filter">
                    <el-form :model="queryParams" label-width="auto">
                        <el-row>
                            <el-col :span="7">
                                <el-form-item label="用户名:">
                                    <el-input style="width: 220px;" maxlength="100" v-model="queryParams.username" placeholder="请输入" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col :span="2">
                                <el-button size="small" icon="el-icon-search" @click="handleQuery"
                                    style="margin: 8px 0 0 20px;" class="btn_primary_color">查询</el-button>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <el-table v-infinite-scroll="loadNextPage" :infinite-scroll-disabled="loadOver" ref="usersTable"
                    :data="userList" border @current-change="handleSelectionChange" style="margin-top: 15px;"
                    :infinite-scroll-distance="100" row-key="id" highlight-current-row>
                    <el-table-column label="用户名" align="left" prop="username" />
                    <el-table-column label="手机号" align="left" prop="phone_no" />
                    <el-table-column label="状态" align="left" prop="statusName" />
                    <el-table-column label="邮箱" align="left" prop="email" />
                    <el-table-column label="联系地址" align="left" prop="address" />
                </el-table>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getUserList } from '@/api/user';
export default {
    data() {
        return {
            queryParams: {
                username: ''
            },
            chooseUsers: [],
            middleUsers: [],
            userList: [],
            pageParam: {
                page: 1,
                num: 10
            },
            total: 0,
            loadOver: false,  //是否加载完
            corp: ''
        }
    },
    props: {
        showChooseUser: {
            type: Boolean
        },
        selectUsers: {
            type: Array,
            default: () => [] // 指定默认值为空数组
        },
        title: {
            type: String,
            default: '选择经办人'
        }
    },
    watch: {
        selectUsers: {
            handler(newVal) {
                // 当 selectUsers 变化时执行的操作
                console.log('selectUsers 已更新', newVal);
                this.middleUsers = newVal
                this.handleSelectRow()
            },
            deep: true // 深度监听数组变化
        }
    },
    created() {
        this.queryParams.corp = this.$store.state.corpId
        this.handleQuery()
    },
    methods: {
        // 多选框选中数据
        handleSelectionChange (selection) {
            this.chooseUsers = [selection]
            this.chooseGoodsOk()
        },
        // 加载下一页数据
        loadNextPage() {
            // 禁用滚动加载
            this.loadOver = true;
            let allPage = 0
            if (this.total === 0) return
            
            if (this.total % this.pageParam.num === 0){  //整除
                allPage = Math.trunc(this.total / this.pageParam.num)
            }else{
                allPage = Math.trunc(this.total / this.pageParam.num) + 1
            }
            console.log(allPage, this.pageParam.page)

            this.pageParam.page ++
            // this.loadOver = false
            if (this.pageParam.page > allPage){
                this.loadOver = true
                return
            }
            this.middleUsers = this.chooseUsers
            this.getUserLists()
        },
        // 按条件筛选
        handleQuery() {
            this.pageParam.page = 1
            this.userList = []
            this.loadOver = false
            this.getUserLists()
        },
        // 获取商品列表
        getUserLists() {
            let that = this
            getUserList(this.queryParams, this.pageParam).then(res => {
                let list = res.data.users.filter(item => {
                    item.statusName = item.is_on_job ? '在职' : '离职'
                    item.is_login_name = item.is_login ? '是' : '否'
                    if (item.role_list.length){
                        item.role_list_name = item.role_list.join('、')
                    }else{
                        item.role_list_name = ''
                    }
                    return item
                })
                that.userList = that.userList.concat(list)
                that.total = res.data.total
                // 合并已选数据
                // that.joinArray()
                // 勾选已选择行
                that.handleSelectRow()
                // 启用滚动加载
                that.loadOver = false;
            })
        },
        joinArray() {
            const map = new Map();
            this.userList.forEach(item => {
                map.set(item.id, { ...item });
            });

            this.selectUsers.forEach(item => {
                if (map.has(item.id)) {
                    const existingItem = map.get(item.id);
                    map.set(item.id, { ...existingItem, ...item });
                } else {
                    map.set(item.id, { ...item });
                }
            });
            this.userList = Array.from(map.values());
        },
        handleSelectRow() {
            let that = this
            this.$nextTick(() => {
                const table = that.$refs.usersTable;
                if (table && table.toggleRowSelection) {
                    table.clearSelection();
                    that.middleUsers.forEach(item => {
                        const rowToSelect = that.userList.find(order => order.id === item.id);
                        if (rowToSelect) {
                            table.setCurrentRow(rowToSelect);
                        }
                    })
                }
            })
        },
        closeDialog() {
            this.chooseUsers = []
            this.$emit('hidden')
        },
        chooseGoodsOk() {
            let res = this.chooseUsers
            this.middleUsers = res
            this.$emit('chooseOK', res)
            this.chooseUsers = []
        },
    }
}
</script>

<style scoped>
    .goods_list {
        padding: 0 10px;
        max-height: 400px;
        overflow-y: auto;
    }
    .btn_primary_color {
        background: #0099ff !important;
        color: #fff !important;
    }
</style>